package org.springcloud.practice.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Random;

@RestController
public class HelloController {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private DiscoveryClient client;

    @GetMapping("/hello")
    public String index() {
        Integer sleepTime = new Random().nextInt(3000);
        logger.info(sleepTime.toString());
        try {
            Thread.sleep(sleepTime);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        List<String> serviceIdList = client.getServices();
        serviceIdList.stream().forEach(serviceId -> {
            List<ServiceInstance> serviceInstanceList = client.getInstances(serviceId);
            serviceInstanceList.stream().forEach(instance -> {
                logger.info("/hello, host: {}, service_id: {}", instance.getHost(), instance.getServiceId());
            });
        });

        return "hello world";
    }
}
